<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>我的店铺</span>
        <div class="extra">
          <el-button type="primary" @click="showAddDrawer('添加商品')">添加商品</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="商品名：">
        <el-input v-model="searchData.name" placeholder="请输入商品名"></el-input>
      </el-form-item>
      <el-form-item label="上架时间：">
        <el-date-picker
            v-model="searchData.pubdate"
            type="date"
            placeholder="请选择上架时间"
        />
      </el-form-item>
      <el-form-item label="类型：">
        <el-select placeholder="请选择" v-model="searchData.typeId">
          <el-option v-for="(type,index) in goodsTypeListData" :key="index" :label="type.name" :value="type.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架：">
        <el-select placeholder="请选择" v-model="searchData.flag">
          <el-option label="上架" value="1"></el-option>
          <el-option label="下架" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getGoodsList">搜索</el-button>
        <el-button @click="resetParams">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 用户列表 -->
    <el-table :data="goodsListData" style="width: 100%">
      <el-table-column label="商品名" prop="name"></el-table-column>
      <el-table-column label="价格" prop="price">
        <template #default="{ row }">
<!--          <el-input v-model="row.price" @blur="updatePrice(row)" />-->
        </template>
      </el-table-column>
      <el-table-column label="上架日期" prop="pubdateStr"></el-table-column>
      <el-table-column label="类型" prop="goodsTypeName"></el-table-column>
      <el-table-column label="简介" prop="intro"></el-table-column>
      <el-table-column label="图片" prop="picture">
        <template #default="{row}">
          <el-image :src="`/api/file/download.do?filename=${row.picture}`"
                    :preview-src-list="[`/api/file/download.do?filename=${row.picture}`]" hide-on-click-modal></el-image>
        </template>
      </el-table-column>
      <el-table-column label="是否上架" prop="flag">
        <template #default="{row}">
<!--          <el-switch v-model="row.flag" @change="toggleStatus(row)" :active-value="1" :inactive-value="0" />-->
        </template>
      </el-table-column>
      <el-table-column label="添加时间" prop="createTimeStr"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showEditDrawer(row,'编辑商品')"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteById(row.id)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5 ,10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
  </el-card>
  <!--  添加 编辑抽屉-->
  <el-drawer v-model="drawerVisible" direction="rtl">
    <template #header>
      <h4>{{titleName}}</h4>
    </template>
    <template #default>
      <el-form ref="form" :rules="rules" :model="formData" label-width="auto" style="max-width: 600px">
        <el-form-item  label="商品名" prop="name">
          <el-input type="text" v-model="formData.name"  />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input type="number" v-model="formData.price"  />
        </el-form-item>
        <el-form-item label="上架时间" prop="pubdate">
          <el-date-picker
              v-model="formData.pubdate"
              type="date"
              placeholder="请选择上架时间"
          />
        </el-form-item>
        <el-form-item label="类型" prop="typeId">
          <el-select  placeholder="请选择" v-model="formData.typeId">
            <el-option v-for="(type,index) in goodsTypeListData" :key="index" :label="type.name" :value="type.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否上架" prop="flag">
          <el-select  placeholder="请选择" v-model="formData.flag">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0"  />
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <el-upload
              class="avatar-uploader"
              action="/api/file/upload.do"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input type="textarea" v-model="formData.intro"  />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick(form)">取消</el-button>
        <el-button type="primary" @click="titleName==='添加商品'?addGoods():editGoods()">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import {onMounted, ref} from "vue";
import {Delete, Edit, Plus} from "@element-plus/icons-vue";
import {deleteGoods, goodsList, goodsTypeList, insertGoods, updateGoods} from "@/api/goods";
import {ElMessage, ElMessageBox} from "element-plus";

// 条件查询数据模型
const searchData = ref({
  name: '',
  pubdate: '',
  typeId: '',
  flag: ''
})
// 添加、编辑表单数据模型
const formData = ref({
  name:'',
  price:'',
  pubdate:'',
  typeId:'',
  intro:'',
  picture:'',
  flag:''
})
const form = ref(null)
//分页条数据模型
const pageNo = ref(1)//当前页
const total = ref(0)//总条数
const pageSize = ref(5)//每页条数
// 商品列表数据集合
const goodsListData = ref([])
// 商品类型列表数据集合
const goodsTypeListData = ref([])
// 控制抽屉显隐
const drawerVisible = ref(false)
// 抽屉title
const titleName = ref('')
// 图片回显url
const imageUrl = ref('')

// 文件上传回调
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  formData.value.picture = response.message
}

const beforeAvatarUpload = (rawFile) => {
  if (!rawFile.type.startsWith('image/')) {
    ElMessage.error('只能上传图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error('图片大小不能超过 20MB!')
    return false
  }
  return true
}

// 添加商品打开抽屉
const showAddDrawer = (title) => {
  titleName.value = title
  drawerVisible.value = true
}
// 条件分页查询商品列表
const getGoodsList = () => {
  const params = {
    params: {
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      ...searchData.value
    }
  }
  goodsList(params).then(res=>{
    if (res.success) {
      goodsListData.value= res.data.records
      total.value = res.data.count
    }
  })
}
// 查询商品类型
const getGoodsTypeList = () => {
  goodsTypeList().then(res=>{
    if (res.success) {
      goodsTypeListData.value= res.data
    }
  })
}
onMounted(()=>{
  getGoodsTypeList()
  getGoodsList()
})
// 重置条件查询表单
const resetParams = () => {
  searchData.value={
    name: '',
    pubdate: '',
    typeId: '',
    flag: ''
  }
  getGoodsList()
}
// 商品编辑
const showEditDrawer = (row, title) => {
  formData.value = {...row}
  imageUrl.value = `/api/file/download.do?filename=${row.picture}`
  titleName.value = title
  drawerVisible.value = true
}
// 商品删除
const deleteById = (id) => {
  ElMessageBox.confirm(
      '确认删除吗，删除后不可恢复?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteGoods({id:id}).then(res=>{
          if (res.success) {
            ElMessage.success(res.message)
            getGoodsList()
          }
        })
      })
      .catch(() => {
      })
}
// 当每页条数发生了变化，会调用
const handleSizeChange = (val) => {
  pageSize.value = val
  getGoodsList()
}
// 当当前页面发生变化，会调用
const handleCurrentChange = (val) => {
  pageNo.value = val
  getGoodsList()
}
//添加商品发送请求
const addGoods=()=>{
  form.value.validate((valid)=>{
    if (valid) {
      insertGoods(formData.value).then(res=>{
        if (res.success) {
          ElMessage.success(res.message)
          drawerVisible.value = false
          getGoodsList()
        }
      })
    }
  })
}
// 编辑商品发送请求
const editGoods=()=>{
  form.value.validate((valid)=>{
    if (valid) {
      updateGoods(formData.value).then(res=>{
        if (res.success) {
          ElMessage.success(res.message)
          drawerVisible.value = false
          getGoodsList()
        }
      })
    }
  })
}
// 取消关闭抽屉
const cancelClick=(formEl)=>{
  drawerVisible.value = false
  formEl.resetFields()
}
// 表单校验
const rules = {
  name: [
    {required: true, message: '请输入商品名', trigger: 'blur'},
    {min: 3, max: 16, message: '长度为3-16位', trigger: 'blur'},
  ],
  price: [
    {required: true, message: '请输入价格', trigger: 'blur'},
  ],
  pubdate: [
    {required: true, message: '请选择上架时间', trigger: 'change'},
  ],
  typeId: [
    {required: true, message: '请选择类型', trigger: 'change'},
  ],
  intro: [
    {required: true, message: '请输入简介', trigger: 'blur'},
  ],
  picture: [
    {required: true, message: '请上传图片', trigger: 'change'},
  ],
  flag: [
    {required: true, message: '请选择是否上架', trigger: 'change'},
  ]
}

// 更新商品价格
const updatePrice = (row) => {
  updateGoods({ id: row.id, price: row.price }).then(res => {
    if (res.success) {
      ElMessage.success('价格更新成功');
    } else {
      ElMessage.error('价格更新失败');
    }
  });
}

// 切换商品上下架状态
const toggleStatus = (row) => {
  updateGoods({ id: row.id, flag: row.flag }).then(res => {
    if (res.success) {
      ElMessage.success(row.flag === 1 ? '商品已上架' : '商品已下架');
    } else {
      ElMessage.error('状态更新失败');
    }
  });
}
</script>

<style scoped lang="scss">
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>